package com.tvunetworks.center.device.controller;

import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.GetSessionUtils;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.annotation.Logined;
import com.tvunetworks.center.device.model.param.DevicePlatformParam;
import com.tvunetworks.center.device.model.param.ListReceiverGridParam;
import com.tvunetworks.center.device.model.param.ListReceiversGridParam;
import com.tvunetworks.center.device.service.DeviceService;
import com.tvunetworks.center.gs.model.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.tvunetworks.center.common.util.ResultUtil.SERVER_EXCEPTION;


/**
 * @program: tvucc-device
 * @description: UserController
 * @author lebronchen
 * @create: 2019-02-28 16:54
 **/
@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 通过Rid查询grid
     * @param param param
     * @return list
     */
    @PostMapping("/listReceiverGrid")
    public Result listReceiverGrid(@RequestBody ListReceiverGridParam param){
        List<Device> list = deviceService.listReceiverGrid(param.getRid());
        return ResultUtil.success(list);
    }

    /**
     * 通过Rid查询grid
     * @param param param
     * @return map
     */
    @PostMapping("/listReceiversGrid")
    public Result listReceiversGrid(@RequestBody ListReceiversGridParam param){
        Map<String, List<Device>> map = deviceService.listReceiversGrid(param.getRids());
        return ResultUtil.success(map);
    }

    /**
     * 根据rid 获取device信息
     * @param peerId peerId
     * @return device
     */
    @GetMapping("/getDevice")
    public Result<Object> getCurrentDevice(@RequestParam String peerId) {
        Device device = deviceService.getCurrentDevice(peerId);
        return ResultUtil.success(device);
    }

    /**
     * 根据rid 获取device信息
     * @param peerIds peerIds
     * @return devices
     */
    @GetMapping("/listDevice")
    public Result<Object> listCurrentDevice(@RequestParam String peerIds) {
        List<Device> devices = deviceService.listCurrentDevice(Arrays.asList(peerIds.split(",")));
        return ResultUtil.success(devices);
    }

    /**
     * 修改Anywhere名字
     * @param peerId peerId
     * @param name name
     * @param request request
     * @return  Result
     */
    @PostMapping("/updateAnywhereName")
    public Result<String> updateAnywhereName(@RequestParam String peerId, @RequestParam String name, HttpServletRequest request){
        String session = GetSessionUtils.getToken(request);
      //  String session = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
        try {

            name = URLDecoder.decode(name,"UTF-8");
            boolean letterDigitOrChinese = isLetterDigitOrChinese(name);
            if(!letterDigitOrChinese){
                return ResultUtil.error("0x000001","The name contains illegal characters or name length more than 128.");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        return deviceService.updateAnywhereName(peerId, name, session);
    }

    /**
     * 修改device名字
     * @param peerId peerId
     * @param name name
     * @param loginUser loginUser
     * @param request request
     * @return Result
     */
    @PostMapping("/editDeviceName")
    public Result<String> updateDeviceName(@RequestParam String peerId, @RequestParam String name, @Logined LoginUser loginUser,HttpServletRequest request){
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        try {


            name = URLDecoder.decode(name,"UTF-8");
            boolean letterDigitOrChinese = isLetterDigitOrChinese(name);
            if(!letterDigitOrChinese){
                return ResultUtil.error("0x000001","The name contains illegal characters or name length more than 128.");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        if(StringUtils.isEmpty(name)){
            return ResultUtil.error("0x000001","name is empty.");
        }
        String session = GetSessionUtils.getToken(request);
      //  String session = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);

        deviceService.globalUpdateDeviceName(peerId, name ,session);
        return ResultUtil.success();
    }

    /**
     *
     * @param str str
     * @return boolean
     */
    public static boolean isLetterDigitOrChinese(String str) {
        //String regex = "^[-_.·a-z0-9A-Z\u4e00-\u9fa5]+$";
//        String regex = "^[-_.,，!。？**·a-z0-9A-Z\u4e00-\u9fa5]{1,20}$";
        String regex = "^[-_.`~!@#$^&*()+=|{}';',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；”“’。，、？·a-z0-9A-Z\u4e00-\u9fa5]{1,128}$";
        return str.matches(regex);
    }

    /**
     *  查询device位置的ip
     * @param ips ips
     * @param peerIds peerIds
     * @param mapType mapType
     * @return Result
     */
   @GetMapping("/listDeviceLocationByMultiIp")
    public Result<String> listDeviceLocationByMultiIp(String ips,String peerIds,String mapType){
        return deviceService.listDeviceLocationByMultiIpOrPeerId(ips,peerIds,mapType);
    }

    /**
     *
     * @param peerIds peerIds
     * @return Result
     */
    @GetMapping("/listGPSByMultiPeerId")
    public Result<String> listGPSByMultiPeerId(String peerIds){
        return deviceService.listGPSByMultiPeerId(peerIds);
    }

    /**
     *
     * @param peerId peerId
     * @return Result
     */
    @GetMapping("/getMetadata")
    public Result<String> getMetadata(@RequestParam("peerId") String peerId){
        try {
            return deviceService.getMetadata(peerId);
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        return ResultUtil.error(SERVER_EXCEPTION);
    }


    /**
     * 查询pack的slotIp
     * @param peerId pack的id
     * @return slotIp集合
     *      * @throws Exception exception
     */
    @PostMapping("listLocalIp")
    public Result listLocalIp(@RequestParam("peerId") String peerId) throws Exception{
        return ResultUtil.success(deviceService.listLocalIp(peerId));
    }


    /**
     * 根据peerid 修改platform
     * @param loginUser  loginUser
     * @param device  peerId和platfrom
     * @return Result
     */
    @PostMapping("updatePlatform")
    public Result updatePlatform(@RequestBody DevicePlatformParam device, @Logined LoginUser loginUser) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return ResultUtil.success(deviceService.updatePlatform(device,loginUser));
    }
}
